/*
 *  Copyright (c) 2018. 玺得（深圳）科技有限公司.保留所有权利. http://www.pi-top.com/ 玺得（深圳）科技有限公司保留所有代码著作权.如有任何疑问请访问官方网站与我们联系. 代码只针对特定需求定制编码，不得在未经允许或授权的情况下对外传播扩散.恶意传播者，法律后果自行承担. 本代码仅用于pps-cloud系统.
 */
package com.pitop.customer.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.fsg.uid.UidGenerator;
import com.pitop.core.base.BaseDAO;
import com.pitop.core.base.BaseSVImpl;
import com.pitop.core.entity.Page;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.exceptions.CustomerException;
import com.pitop.customer.dao.CustomerAddressDAO;
import com.pitop.customer.dao.CustomerDAO;
import com.pitop.customer.entity.Customer;
import com.pitop.customer.entity.CustomerAddress;
import com.pitop.customer.entity.CustomerState;
import com.pitop.customer.entity.CustomerSyncState;
import com.pitop.sync.entity.SyncTraceModel;
import com.pitop.sync.entity.SyncTraceState;
import com.pitop.sync.service.SyncDataTraceSV;
import com.pitop.sync.service.SyncTraceSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("customerSV")
@Slf4j
public class CustomerSVImpl extends BaseSVImpl<Customer, Long> implements CustomerSV {

    @Autowired
    private CustomerDAO customerDAO;

    @Autowired
    private CustomerAddressDAO customerAddressDAO;

    @Autowired
    private SyncTraceSV syncTraceSV;

    @Autowired
    private SyncDataTraceSV syncDataTraceSV;


    @Resource
    private UidGenerator uidGenerator;

    @Override
    protected BaseDAO getBaseDAO() {
        return customerDAO;
    }

    /**
     * 保存account对象
     *
     * @param entity 实体
     * @throws BaseException
     */
    @Override
    public void save(Customer entity) throws BaseException {
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        super.save(entity);
    }

    /**
     * 加载一个对象Customer
     *
     * @param id
     * @return Customer
     */
    @Override
    public Customer load(Long id) {
        if (id == null) {
            throw new CustomerException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        return customerDAO.load(param);
    }

    /**
     * 加载一个对象Customer 通过id
     *
     * @param id
     * @return Customer
     */
    @Override
    public Customer loadById(Long id) {
        if (id == null) {
            throw new CustomerException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return customerDAO.loadById(id);
    }

    @Override
    public Customer loadByCode(String code) {
        if (StringUtils.isEmpty(code)) {
            throw new CustomerException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> params = new HashedMap();
        params.put("code", code);
        return customerDAO.load(params);
    }


    /**
     * 根据主键id,oldStates 共同更新 Customer 的状态到newState状态
     *
     * @param id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
    public void updateStateById(Long id, CustomerState newState, CustomerState... oldStates) {
        if (id == null) {
            throw new CustomerException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new CustomerException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new CustomerException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        customerDAO.updateStateById(id, new Date(), newState.name(), states);
    }

    /**
     * 根据主键id 更新 Customer 的状态到另一个状态
     *
     * @param id
     * @param state 状态
     */
    @Override
    public void updateById(Long id, CustomerState state) {
        if (id == null) {
            throw new CustomerException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        customerDAO.updateById(id, state.name(), new Date());
    }


    /**
     * 删除对象Customer
     *
     * @param id
     * @return Customer
     */
    @Override
    public void delete(Long id) {
        if (id == null) {
            throw new CustomerException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        customerDAO.delete(param);
    }


    /**
     * 查询Customer分页
     *
     * @param customer 对象
     * @param offset   查询开始行
     * @param limit    查询行数
     * @return List<Customer>
     */
    @Override
    public List<Customer> list(Customer customer, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }

        Map<String, Object> map = null;
        if (customer != null) {
            map = JSON.parseObject(JSON.toJSONString(customer, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return customerDAO.list(map, new RowBounds(offset, limit));
    }

    @Override
    public int count(Customer customer) {
        Map<String, Object> map = null;
        if (customer != null) {
            map = JSON.parseObject(JSON.toJSONString(customer, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return customerDAO.count(map);
    }

    /**
     * 查询Customer分页
     *
     * @param id
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<Customer>
     */
    @Override
    public List<Customer> list(Long id, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        return customerDAO.list(param, new RowBounds(offset, limit));
    }

    @Override
    public int count(Long id) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        return customerDAO.count(param);
    }

    /**
     * 从pps向pps-cloud同步用户数据
     * 1.验证数据合法性
     * 2.同步用户数据
     * 3.同步用户地址数据
     * 4.返回结果
     *
     * @param customerList 参数信息
     * @return boolean
     */
    @Override
    public boolean upwardsSyncCustomer(List<Customer> customerList) {
        //1.验证数据合法性
        if (customerList == null || customerList.size() <= 0) {
            return false;
        }
        try {
            List<CustomerAddress> customerAddressList;
            Map<String, Object> params;
            Customer customerFlag;
            for (Customer customer : customerList) {
                customerFlag = customerDAO.loadByCode(customer.getCode());
                //2.同步用户数据
                if (customerFlag == null) {
                    customer.setSyncState(CustomerSyncState.Synced.name());
                    customerDAO.insert(customer);
                } else {
                    customer.setSyncState(CustomerSyncState.Synced.name());
                    customerDAO.update(customer);
                }
                //记录同步追踪用户数据
                String desc = SyncTraceState.UpwardSyncCustomer.val + ",数据模型[" + SyncTraceModel.Customer.name() + "],用户编码-工厂编码[" + customer.getCode() + "-" + customer.getFactoryCode() + "]";
                String syncTraceCode = syncTraceSV.saveSyncTrace(customer.getFactoryCode(), SyncTraceState.SyncSuccess.name(),
                        SyncTraceState.UpwardSync.name(), SyncTraceModel.Customer.name(), customer.getCode(), desc);
                //记录同步用户数据日志
                syncDataTraceSV.saveSyncDataTrace(syncTraceCode, customer);

                //3.同步用户地址数据
                customerAddressList = customer.getCustomerAddresses();
                if (customerAddressList != null && customerAddressList.size() > 0) {
                    params = new HashedMap();
                    params.put("customerCode", customer.getCode());
                    customerAddressDAO.delete(params);
                    customerAddressDAO.batchInsert(customerAddressList);
                }
            }
            return true;
        } catch (Exception e) {
            Customer customer = customerList.get(0);
            String desc = SyncTraceState.UpwardSyncCustomer.val + ",数据模型[" + SyncTraceModel.Customer.name() + "],用户编码-工厂编码[" + customer.getCode() + "-" + customer.getFactoryCode() + "]";
            String syncTraceCode = syncTraceSV.saveSyncTrace(customer.getFactoryCode(), SyncTraceState.SyncFailed.name(),
                    SyncTraceState.UpwardSync.name(), SyncTraceModel.Customer.name(), customer.getCode(), desc);
            //记录同步用户数据日志
            syncDataTraceSV.saveSyncDataTrace(syncTraceCode, customer);
            return false;
        }
    }

}
